package com.cens.mall.commodity.service.impl;

import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cens.common.utils.PageUtils;
import com.cens.common.utils.Query;

import com.cens.mall.commodity.dao.ProductAttrValueDao;
import com.cens.mall.commodity.entity.ProductAttrValueEntity;
import com.cens.mall.commodity.service.ProductAttrValueService;
import org.springframework.transaction.annotation.Transactional;


@Service("productAttrValueService")
public class ProductAttrValueServiceImpl extends ServiceImpl<ProductAttrValueDao, ProductAttrValueEntity> implements ProductAttrValueService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<ProductAttrValueEntity> page = this.page(
                new Query<ProductAttrValueEntity>().getPage(params),
                new QueryWrapper<ProductAttrValueEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void saveProductAttr(List<ProductAttrValueEntity> productAttrValueEntities) {
        this.saveBatch(productAttrValueEntities);
    }

    @Override
    public List<ProductAttrValueEntity> baseAttrListForSpu(Long spuId) {
        return this.baseMapper.selectList(
                new QueryWrapper<ProductAttrValueEntity>()
                        .eq("spu_id", spuId)
        );
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateSpuAttr(Long spuId, List<ProductAttrValueEntity> entities) {
        this.baseMapper.delete(
                new QueryWrapper<ProductAttrValueEntity>()
                    .eq("spu_id",spuId)
        );
        List<ProductAttrValueEntity> productAttrValueEntities = entities.stream()
                .map(
                        entity -> {
                            entity.setSpuId(spuId);
                            return entity;
                        }
                ).collect(Collectors.toList());
        saveBatch(productAttrValueEntities);
    }

}